import util from "../../utils/util";
import {routerFilter} from "../../utils/routerFilter";
import consts from "../../js/const";
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

routerFilter({

    /**
     * 页面的初始数据
     */
    data: {
        pageNumber: 1,
        pageSize: 5,
        locationImageUrl:consts.getImageUrl("location.png")
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let gun=function (name, url){
            if (!url) url = location.href;
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            let regexS = "[\\?&]" + name + "=([^&#]*)";
            let regex = new RegExp(regexS);
            let results = regex.exec(url);
            return results == null ? null : results[1];
        }
        let that = this;
        if (options.q) {
            let url = decodeURIComponent(options.q);
            let orderNum = gun('orderNum', url);
            util.promise('/verificationOrder?orderNum='+orderNum, {isRequestParam:true,method:'GET'}).then((res)=>{
               if(res.data){
                   Toast({
                       type: 'success',
                       message: `订单[${orderNum}]核销成功`,
                       onClose: () => {
                           that.refreshOrder();
                       },
                   });
               }
           })
        }else{
            const eventChannel = this.getOpenerEventChannel();
            eventChannel.on('acceptDataFromOpenerPage', function (data) {
                if (data) {
                    if(data.isVerification){
                        wx.setNavigationBarTitle({
                            title: '核销订单列表'
                        })
                    }

                    that.setData(data, () => {
                        if(data.index===0 || data.isVerification){
                            that.refreshOrder();
                        }
                    });
                }
            });
        }

    },
    searchOrder(e) {
        let data = this.data;
        data.pageNumber = 1;
        data.payStatus = null;
        data.statusList = null;
        data.status = null;
        data.payStatusList = null;
        if (e.detail.index === 1) {
            data.payStatus = 'UNPAID';
            data.statusList = "SUBMITED,CONFIRM";
        } else if (e.detail.index === 2) {
            data.payStatus = 'PAID';
            data.status = 'CONFIRM';
        } else if (e.detail.index === 3) {
            data.status = 'COMPLETED';
            data.payStatus = 'PAID';
        } else if (e.detail.index === 4) {
            data.statusList = "SUBMITED,CONFIRM,REJECT";
            data.payStatusList = 'PAID,UNPAID,REFUNDING';
        }
        data.hasData = true;
        data.orderList = null;
        this.setData(data, () => {
            this.refreshOrder();
        });

    },
    refreshOrder(isAllRefresh) {
        let that = this;
        let data = that.data;
        let params = util.extend({}, data);
        util.promise('/searchOrders', params).then(function (res) {
            let hasData = res.data && !util.isEmptyObject(res.data.list);
            that.setData({loading: false, hasData: hasData});
            if (hasData) {
                let orderList = res.data.list;
                orderList.forEach(function (order) {
                    order.qrUrl = consts.HOST_NAME + '/wechat/genQRCode?orderNum=' + order.orderNum;
                });
                isAllRefresh? that.setData({orderList: orderList }): that.setData({orderList: orderList.concat(data.orderList || [])});
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('refreshData', null);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    payOrder(e) {
        let eycOrder = e.currentTarget.dataset.eycOrder;
        let payParams = {
            totalFee: eycOrder.price * 100,
            openid: eycOrder.openid,
            outTradeNo: eycOrder.orderNum
        };
        let that=this;
        util.promise('/pay/payOrder', payParams).then(res => {
            let data = res.data;
            if (data) {
                wx.requestPayment({
                    timeStamp: data.timeStamp,
                    nonceStr: data.nonceStr,
                    package: data.packageValue,
                    signType: data.signType,
                    paySign: data.paySign,
                    success(res) {
                        that.removeEycOrder(eycOrder);
                    },
                    fail(res) {
                       Toast('订单支付失败');
                    }
                })
            }
        })
    },
    cancelOrder(e) {
        let that = this;
        let eycOrder = e.currentTarget.dataset.eycOrder;
        Dialog.confirm({
            title: '取消订单',
            message: '是否确认取消订单',
        }).then(() => {
            util.promise('/cancelOrder', eycOrder.orderNum).then(res => {
                if (res.data) {
                    that.removeEycOrder(eycOrder);
                    Toast({
                        type: 'success',
                        message: '订单取消成功',
                        onClose: () => {
                            that.refreshOrder(true);
                        },
                    });
                }
            });

        }).catch(() => {
            Dialog.close();
        });
    },
    removeEycOrder(eycOrder){
        let that=this;
        let orderList=that.data.orderList;
        util.removeObjectByValue(orderList,eycOrder.orderNum,'orderNum');
        that.setData({orderList:orderList});
    },
    scrollToLower: function (e) {
        let that = this;
        let data = that.data;
        if (data.hasData) {
            that.setData({loading: true, pageNumber: data.pageNumber + 1}, () => {
                that.refreshOrder();
            });
        }
    },
    makePhoneCall(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phoneNumber
        })
    },
    refund(e) {
        // let that = this;
        let eycOrder = e.currentTarget.dataset.eycOrder;
        wx.navigateTo({
            url: '/pages/order/orderRefund',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                refreshOrder: function () {
                    that.refreshOrder();
                 }
            },
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                 res.eventChannel.emit('acceptDataFromOpenerPage', { eycOrder: eycOrder})
            }
        })
        // let eycOrder = e.currentTarget.dataset.eycOrder;
        // let refundParams = {
        //     totalFee: 1/*eycOrder.price * 100*/,
        //     refundFee: 1,
        //     openid: eycOrder.openid,
        //     outTradeNo: eycOrder.orderNum,
        //     outRefundNo: eycOrder.orderId,
        //     opUserId: eycOrder.orderNum
        // };
        // let that = this;
        // util.promise('/pay/refund', refundParams).then(res => {
        //     if (res.data) {
        //         that.removeEycOrder(eycOrder);
        //         Toast('订单退款成功~');
        //     }
        // });
    },
    editOrder(event){
        let that = this;
        let eycOrder = event.currentTarget.dataset.eycOrder;
        wx.navigateTo({
            url: '/pages/vehicle/checkVehicle?isEdit=true',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptVehicleFileFromItemsPage: function (vehicleFile) {
                    that.refreshVehicleFile(vehicleFile);
                }
            },
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                 res.eventChannel.emit('acceptDataFromOrderListPage', eycOrder)
            }
        })
    }
});